//
//  MenuManagementVC.m
//  reSearchDemo
//
//  Created by 科技 on 15/8/18.
//  Copyright (c) 2015年 Kiwaro. All rights reserved.
//

#import "MenuManagementVC.h"
#import "MenuCell.h"
#import "ADDmenuVC.h"
#import "MenuView.h"
#import "MenuDetails.h"
@interface MenuManagementVC ()<UITableViewDataSource,UITableViewDelegate> {
    UITableView *_tableView;
    NSMutableArray *_dataSource;   /**< 数据源 */
    NSMutableArray *deleteArr;     /**< 存放删除的数据 */
    UIButton *deleteBtn;           /**< 编辑按钮 */
    MenuView *_menuView;
    NSMutableArray *cellArr;       /**< 存放cell的数组 */
    NSMutableArray *upData;        /**< 存放上传服务器数组 */
    NSMutableArray *MenuData;      /**< 存放menu的数据  */
}

@end

@implementation MenuManagementVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"菜单管理";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(AddRightBtnAction:)];

    [self allocTableView];
    [self loadDataSource];
    
}
//初始化tableview
- (void)allocTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -20, ViewWIDTH(self.view), ViewHEIGHT(self.view)) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
//    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [self.view addSubview:_tableView];
    cellArr = [NSMutableArray array];
}
//加载数据
- (void)loadDataSource {
    _dataSource = [NSMutableArray array];
    /*
    NSString *path = @"MobilePort/index/menusetting.html";
    [[HTTPGlobals shareHTTPGlobal] GetHTTPRequest:path parameters:nil finish:^(BOOL seccess, NSString *error, id obj) {
        if (seccess) {
            DLog(@"菜单数据:  %@",obj);
            NSArray *arr = obj[@"user_menudata"];
            //取一级菜单
            for (NSDictionary *dic in arr) {
                DLog(@"name = %@",dic[@"name"]);
                NSArray *arr = dic[@"list"];
                
                //添加完子菜单在添加主菜单
                NSDictionary *menu = @{@"name":dic[@"name"],@"type":@"0",@"subcount":[NSString stringWithFormat:@"%ld",(long)arr.count],@"link":dic[@"link"],@"menuid":dic[@"menuid"]};
                [_dataSource addObject:menu];
                //取二级菜单
                if (arr.count) {
                    for (NSDictionary *subDic in arr) {
                        NSDictionary *subMenu = @{@"name":subDic[@"name"],@"type":@"1",@"link":subDic[@"link"],@"menuid":subDic[@"menuid"]};
                        [_dataSource addObject:subMenu];
                    }
                }
            }
            [_tableView reloadData];
        }
        
    }];
     */
}
#pragma mark --添加按钮点击事件--
- (void)AddRightBtnAction:(UIBarButtonItem *)sender {
    NSMutableArray * arr = [NSMutableArray array];
//    MenuData = [NSMutableArray array];
//    [arr addObject:@"主菜单添加"];
//    [MenuData addObject:@"主菜单"];
//    [_dataSource enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        if (![obj[@"type"] intValue]) {
//            [arr addObject:[NSString stringWithFormat:@"%@分类",obj[@"name"]]];
//            [MenuData addObject:obj];
//        }
//    }];
    
    [arr addObject:@"主菜单1"];
    [arr addObject:@"主菜单2"];
    [arr addObject:@"主菜单3"];
    _menuView = [[MenuView alloc] initWithButtonTitles:arr withDelegate:self];
    _menuView.hasImage = NO;
    [_menuView showInView:self.view origin:CGPointMake(self.view.width - 180, 70)];
    _menuView.buttonView.delegate=self;
    
}
#pragma mark --编辑按钮点击事件--
- (void)releaseBtnAction:(UIButton *)sender {
    if (!sender.selected) {
        
//        _tableView.allowsSelectionDuringEditing = YES;//进入删除状态
        _tableView.allowsMultipleSelectionDuringEditing = YES; //进入多选删除状态
        [_tableView setEditing:YES animated:YES]; //将tableview设置为可编辑
        sender.selected = YES;
        
    }else {
        sender.selected = NO;
//        _tableView.allowsSelectionDuringEditing = NO;//取消删除状态
        _tableView.allowsMultipleSelectionDuringEditing = NO; //取消多选删除状态
        [_tableView setEditing:NO animated:YES]; //将tableview设置为不可编辑状态
        if (!deleteArr.count) {
            return;
        }
        
         //通过post请求上传menuid删除菜单
        [upData removeAllObjects];
        upData = nil;
        upData = [NSMutableArray arrayWithArray:deleteArr];
        NSInteger subCount = 0;
        NSInteger row = 0;
        //判断选中菜单的类型
        for (NSIndexPath *indexPath in deleteArr) {
            NSDictionary *dic = _dataSource[indexPath.row];
            
            if (![dic[@"type"] intValue]) {
                subCount = [dic[@"subcount"] integerValue];
                row = indexPath.row;
            }
        }
        //筛选出post需要删除的菜单
        NSInteger SelectSubcount;
        for (int i = 1; i<= subCount; i++) {
            for (int j = 0;j < upData.count;j++) {
                NSIndexPath *CellPath = upData[j];
                if (CellPath.row == row + i) {
                    SelectSubcount ++;
                    [upData removeObjectAtIndex:j];
                }
            }
        }
        //筛选出tableview需要删除的行
        if (SelectSubcount != subCount) {
            [deleteArr removeAllObjects];
            deleteArr =nil;
            deleteArr = [NSMutableArray arrayWithArray:upData];
            for (int i = 1; i<= subCount; i++) {
                NSIndexPath *p = [_tableView indexPathForCell:cellArr[row +i]];
                DLog(@"p = %@",p);
                
                [deleteArr addObject:p];
            }
        }
        //选中的行
        NSArray *selectedRows = [NSArray arrayWithArray:deleteArr];
        DLog(@"selectedRows = %@",selectedRows);
        NSMutableIndexSet *indicesOfItemsToDelete = [NSMutableIndexSet new];
        for (NSIndexPath *selectionIndex in selectedRows) {
            [indicesOfItemsToDelete addIndex:selectionIndex.row];
        }
        //post服务器删除菜单
        __block NSInteger upCount = 0;
        for (NSIndexPath *UPRow in upData) {
            NSDictionary *data = _dataSource[UPRow.row];
            NSDictionary *parme = @{@"menuid":data[@"menuid"]};
            NSString *path;
            if (![data[@"type"] intValue]) {
                path = @"MobilePort/Index/del_menu_type_0";
            }else {
                path = @"MobilePort/Index/del_menu_type_1";
            }
            [[HTTPGlobals shareHTTPGlobal] PostHTTPRequest:path parameters:parme finish:^(BOOL seccess, NSString *error, id obj) {
                if (seccess) {
                    upCount++;
                    if (![obj[@"code"] intValue]) {
                        if (upCount == upData.count) {
                            //从数据源中删除所选行对应的值
                            [_dataSource removeObjectsAtIndexes:indicesOfItemsToDelete];
                            [cellArr removeObjectsAtIndexes:indicesOfItemsToDelete];
                            //删除所选的行
                            [_tableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
                            DLog(@"删除菜单成功 : %@",obj);
                            [self showText:@"删除成功"];
                            [self loadDataSource];
                        }else {
                            [self showText:@"删除失败"];
                        }
                    }
                    
                }else {
                    UIAlertView *alert = [self showDefaultAlertView];
                    [alert show];
                }
            }];
        }
       
        
        [deleteArr removeAllObjects];
        deleteArr = nil;
    }

}
#pragma mark -
#pragma mark --tableViewDelegate--
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 9;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *indentifier = @"cell";
    MenuCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        cell = [[MenuCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:indentifier];
        [cellArr addObject:cell];
    }
    if ([_dataSource[indexPath.row][@"type"]intValue]) {
        cell.menuType = subMenu;
    }else {
        cell.menuType = firstMenu;
    }
    cell.name = _dataSource[indexPath.row][@"name"];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!deleteBtn.selected) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    if (tableView == _menuView.buttonView) {
        if (_menuView.buttonTitles.count == 4 && indexPath.row == 0) {
            [self showText:@"菜单最多创建三个"];
            return;
        }
        if (indexPath.row != 0) {
            if ([MenuData[indexPath.row][@"subcount"]intValue] == 5 && indexPath.row != 0) {
                [self showText:@"分类最多创建五个"];
                return;
            }
        }
        
        
        ADDmenuVC *addmenu = [[ADDmenuVC alloc] init];
        [self pushViewController:addmenu];
        if (indexPath.row == 0) {
            NSDictionary *dic = @{@"name":MenuData[indexPath.row],@"type":@"menu"};
            addmenu.menuDic = dic;
        }else {
            addmenu.menuDic = MenuData[indexPath.row];
        }
        addmenu.loadBlcok = ^(BOOL seccess) {
            //更新数据源
            [self loadDataSource];
        };
        [_menuView hide];
        return;
    }
    if (!deleteBtn.selected) {
        MenuDetails *menuDetails = [[MenuDetails alloc] init];
        menuDetails.menuDic = _dataSource[indexPath.row];
        return;
    }
    /*
    NSDictionary *dic = _dataSource[indexPath.row];
    DLog(@"dic = %@",dic);
    if ([dic[@"subcount"] intValue]) {
        for (int i = 1; i<= [dic[@"subcount"] intValue]; i++) {
            NSDictionary *subDic = _dataSource[indexPath.row +i];
            MenuCell *cell = cellArr[indexPath.row + i];
            cell.menuType = subMenu;
            cell.name = subDic[@"name"];
            cell.selected = YES;
        }
    }
     */
    [self updateDeleteData];
}
//取消选中方法
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!deleteBtn.selected) {
        return;
    }
    [self updateDeleteData];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (!_dataSource.count) {
        return nil;
    }
    UIView *HeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ViewWIDTH(self.view), 64)];
    deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(10, 10, ViewWIDTH(self.view) - 20, 44);
    [deleteBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [deleteBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [deleteBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [deleteBtn setTitle:@"删除" forState:UIControlStateSelected];
    [deleteBtn addTarget:self action:@selector(releaseBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [deleteBtn setBackgroundColor:[UIColor lightGrayColor]];
    [HeadView addSubview:deleteBtn];
    return HeadView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (!_dataSource.count) {
        return 0.0;
    }
    return 64;
}
#pragma mark - 更新选中cell数组--
- (void)updateDeleteData
{
    NSArray *selectedRows = [_tableView indexPathsForSelectedRows];
    
    deleteArr = [NSMutableArray arrayWithArray:selectedRows];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
